' SCRIPT PARAMETERS
'	0: CONFIG settings file
'   1: SOURCE web.config file
' 	2: OUTPUT path
' 	3: The "environment" to copy and replace settings from
' 

option explicit
'on error resume next

if WScript.Arguments.Count < 4 then
    WScript.Echo "Missing script parameters"
    WScript.quit
end if

dim paramCfg: paramCfg = WScript.Arguments(0)
dim paramSrc: paramSrc = WScript.Arguments(1)
dim paramOut: paramOut = WScript.Arguments(2)
dim paramEnv: paramEnv = WScript.Arguments(3)

WScript.Echo "CFG: " & paramCfg
WScript.Echo "SRC: " & paramSrc
WScript.Echo "OUT: " & paramOut
WScript.Echo "ENV: " & paramEnv

dim cfgXmlDoc: set cfgXmlDoc = CreateObject("MSXML2.DomDocument.6.0")
dim srcXmlDoc: set srcXmlDoc = CreateObject("MSXML2.DomDocument.6.0")
cfgXmlDoc.async = false
srcXmlDoc.async = false

dim fso: set fso = CreateObject("Scripting.FileSystemObject")

if fso.FileExists(paramCfg) and fso.FileExists(paramSrc) then
	if cfgXmlDoc.load(paramCfg) and srcXmlDoc.load(paramSrc) then
		if cfgXmlDoc.parseError.errorCode <> 0 Then
			WScript.Echo "ERROR: " & cfgXmlDoc.parseError.errorCode
		elseif srcXmlDoc.parseError.errorCode <> 0 Then
			WScript.Echo "ERROR: " & srcXmlDoc.parseError.errorCode
		else
			dim cfgXmlNode: set cfgXmlNode = cfgXmlDoc.documentElement.selectSingleNode("/deploySettings")
			dim childNode

			dim found: found = false
			For Each childNode in cfgXmlNode.childNodes
				if childNode.getAttribute("name") = paramEnv then
					found = true
					exit for
				end if
			Next

			dim str: str = ""
			if found then

				'
				' TODO:
				' 1. Load the paramSrc file
				' 2. Iterate through each settings in childNode
				' 3. Replace cfgXmlNode values from paramSrc file with values from childNode
				' 4. Save file to paramOut
				'

				dim settingsNode
				For Each settingsNode in childNode.childNodes
					str = str & " -- " & settingsNode.getAttribute("name") & "=" & settingsNode.getAttribute("value") & "  "

					dim srcXmlNode: set srcXmlNode = srcXmlDoc.documentElement.selectSingleNode(settingsNode.getAttribute("path"))

					dim srcXmlChildNode

					For Each srcXmlChildNode in srcXmlNode.childNodes
						' TODO:
						' 3. Replace cfgXmlNode values from paramSrc file with values from childNode
						str = str & " SRC: " & srcXmlChildNode.getAttribute("value")
					Next

					set srcXmlChildNode = nothing
					set srcXmlNode = nothing
				Next

				WScript.Echo str
				set settingsNode = nothing
			else
				WScript.Echo "Environment not found: " & paramEnv
			end if

			set str = nothing
			set childNode = nothing
			set cfgXmlNode = nothing
		end if
	else
		WScript.Echo "ERROR: File not loaded"
	end if
else
	WScript.Echo "ERROR: File does not exist"
end if

set paramCfg = nothing
set paramSrc = nothing
set paramOut = nothing
set paramEnv = nothing

set fso = nothing
set cfgXmlDoc = nothing